package com.faithnmn.phone;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.faithnmn.phone.model.PhoneItem;
import com.tjerkw.slideexpandable.library.ActionSlideExpandableListView;

public class MainActivity extends Activity {
	public TextView outputText;
	private Cursor phoneCursor;
	private Cursor emailCursor;
	private String contact_id;
	private String name;
	private ProgressDialog progress;
	private Handler handler= new Handler();
	private ActionSlideExpandableListView list;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		outputText = (TextView) findViewById(R.id.textView1);
		outputText.setText("");
		progress = new ProgressDialog(this);
		progress.setMessage("Loading..");
		progress.setCancelable(false);
		list = (ActionSlideExpandableListView)this.findViewById(R.id.list);
		new LoadContactAsyn().execute();
	}
	
	private class LoadContactAsyn extends AsyncTask<Void, Void, ArrayList<PhoneItem>>{
		private PhoneItemAdapter adapter;
		@Override
		protected void onPreExecute() {
			progress.show();
		}
		@Override
		protected ArrayList<PhoneItem> doInBackground(Void... params) {
			return fetchContacts();
		}
		@Override
		protected void onPostExecute(ArrayList<PhoneItem> result) {
			progress.dismiss();
			if(result!=null && result.size()>0){
				
			}else{
				return;
			}
			adapter= new PhoneItemAdapter(MainActivity.this,R.layout.expandable_list_item,R.id.text, result);
			list.setAdapter(adapter);
			list.setItemActionListener(new ActionSlideExpandableListView.OnActionClickListener() {
				@Override
				public void onClick(View listView, View buttonview, int position) {
					String actionName = "";
					if(buttonview.getId()==R.id.call) {
						actionName = "Call";
					} else if(buttonview.getId()==R.id.message) {
						actionName = "Message";
					}else{
						actionName = "Copy Text";
					}
					Toast.makeText(
						MainActivity.this,
						"Clicked Action: "+actionName+" in list item "+position,
						Toast.LENGTH_SHORT
					).show();
				}

			}, R.id.call, R.id.message,R.id.copyText);
		}
	}
	
	private Runnable changeMsgLoading = new Runnable() {
		@Override
		public void run() {
			progress.setMessage(getResources().getString(R.string.loading_param, (++current)+"/"+total));
		}
	};
	private int total;
	private int current;
	
	public ArrayList<PhoneItem> fetchContacts() {
		ArrayList<PhoneItem> items = new ArrayList<PhoneItem>();
		String phoneNumber = null;
		String email = null;
		Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
		String _ID = ContactsContract.Contacts._ID;
		String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
		String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
		Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
		String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
		Uri EmailCONTENT_URI =  ContactsContract.CommonDataKinds.Email.CONTENT_URI;
		String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
		String DATA = ContactsContract.CommonDataKinds.Email.DATA;
		
		StringBuffer output = new StringBuffer();
		ContentResolver contentResolver = getContentResolver();
		Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);	
		
		// Loop for every contact in the phone
		if (cursor.getCount() > 0) {
			total=cursor.getCount();
			current = 0;
			while (cursor.moveToNext()) {
				handler.post(changeMsgLoading);
				contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
				name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
				int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
				if (hasPhoneNumber > 0) {
					output.append("\n First Name:" + name);
					// Query and loop for every phone number of the contact
					phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
					while (phoneCursor.moveToNext()) {
						phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
						output.append("\n Phone number:" + phoneNumber);
						PhoneItem item= new PhoneItem();
						item.phoneName = name;
						item.phoneNumber = phoneNumber;
						items.add(item);
					}
					phoneCursor.close();
//					// Query and loop for every email of the contact
//					emailCursor = contentResolver.query(EmailCONTENT_URI,	null, EmailCONTACT_ID+ " = ?", new String[] { contact_id }, null);
//					while (emailCursor.moveToNext()) {
//						email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
//						output.append("\nEmail:" + email);
//					}
//					emailCursor.close();
				}
				output.append("\n");
			}
			
			return items;
		}
		return  items;
	}

}